package a04_字符串;

/**
 * <p>
 * a02_反转字符串2
 * </p>
 *
 * @author flyduck
 * @since 2024-07-09
 */
public class a02_反转字符串2复习3 {
    public static void main(String[] args) {
        System.out.println(reverseStr("abcdefg", 2));
    }


    // abcdefghi  3
    public static String reverseStr(String source, int k) {
        char[] chars = source.toCharArray();
        //a
        for (int i = 0; i < chars.length; i = (i + 2*k)) {//0-3 翻转0-1   4-7 反转4-5
            if((i + k - 1) <= (chars.length - 1)){//终止索引没到最后
                reverse(chars, i, i + k - 1);
            }else {//终止索引大于最后一个索引
                reverse(chars, i, chars.length - 1);
            }
        }
        return new String(chars);
    }

    private static void reverse(char[] chars,int leftIdx,int rightIdx){
        while (leftIdx < rightIdx) {
            char temp = chars[leftIdx];
            chars[leftIdx] = chars[rightIdx];
            chars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

}
